import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_acrylic/flutter_acrylic.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:window_example/util/window_util.dart';
import 'package:window_example/page_navigation/body_widget.dart';
import 'package:window_example/widget/titlebar_widget.dart';
import 'package:window_manager/window_manager.dart';

var key = GlobalKey();
Color color = Platform.isWindows ? const Color(0xb3ffffff) : Colors.transparent;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Must add this line.
  await windowManager.ensureInitialized();
  await Window.initialize();
  WindowOptions windowOptions = const WindowOptions(
    minimumSize: Size(400, 300),
    // maximumSize: Size(400, 300),
    //window 限制最小尺寸
    size: Size(800, 500),
    //
    center: true,
    // backgroundColor: Colors.transparent,
    // window 背景颜色，默认设置为透明就好
    skipTaskbar: false,
    //true 表示在状态栏不显示该应用
    alwaysOnTop: false,
    //true 表示设置Window一直位于最顶层
    titleBarStyle: TitleBarStyle.hidden,
    ////hidden 表示隐藏TitleBar（缩放、关闭）
    title: "WindowSettingTest",
    //设置窗口的标题，
    windowButtonVisibility: true, //隐藏
  );

  // doWhenWindowReady(() async {
  //   final win = appWindow;
  //   const initialSize = Size(600, 450);
  //   win.minSize = initialSize;
  //   win.size = initialSize;
  //   win.alignment = Alignment.center;
  //   win.title = "Custom window with Flutter";
  //
  //   InterfaceBrightness brightness =
  //   Platform.isMacOS ? InterfaceBrightness.auto : InterfaceBrightness.dark;
  //   await Window.setEffect(
  //       effect: WindowEffect.acrylic,
  //       color: color,
  //       dark: brightness == InterfaceBrightness.dark);
  //   if (Platform.isMacOS) {
  //     if (brightness != InterfaceBrightness.auto) {
  //       Window.overrideMacOSBrightness(
  //         dark: brightness == InterfaceBrightness.dark,
  //       );
  //     }
  //   }
  //   win.show();
  // });

  windowManager.waitUntilReadyToShow(windowOptions, () async {
    await windowManager.show();
    await windowManager.focus();
    windowManager.setResizable(true); //设置窗口不可缩放
    windowManager.setAspectRatio(2); //设置窗口宽高比
    windowManager.setHasShadow(true);
    windowManager.setBrightness(Brightness.light);
  });
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MyHomePage(title: "ssss");
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with WindowListener, TrayListener {
  var isAutoStart = false;
  Timer? _timer;
  bool _toogleTrayIcon = true;

  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
    trayManager.addListener(this);
    _init();
    // _initSystemTray();
  }


  Future<void> _init() async {
    //设置系统托盘图标
    await trayManager.setIcon(
      Platform.isWindows
          ? 'assets/images/tray_icon_original.ico'
          : 'assets/images/img_1.png',
    );
    //设置系统托盘的标题
    trayManager.setTitle("system tray");
    //设置系统托盘的标题
    trayManager.setToolTip("How to use system tray with Flutter:鼠标滑过提示");
    //系统托盘的位置 ：仅适用MacOS
    trayManager.setIconPosition(TrayIconPositon.right);
    //设置系统托盘的菜单
    Menu menu = Menu(
      items: [
        //设置系统托盘的子菜单
        MenuItem.submenu(
            key: 'window_settings',
            label: '窗口设置',
            icon: Platform.isWindows
                ? 'assets/images/app_icon.bmp'
                : 'assets/images/img_1.png',
            submenu: Menu(items: [
              MenuItem.checkbox(
                checked: true,
                label: "毛玻璃效果",
                onClick: (MenuItem menuItem) {
                  menuItem.checked = !(menuItem.checked == true);
                  if (kDebugMode) {
                    print("毛玻璃效果 onClick ${menuItem.checked}");
                  }
                  if (menuItem.checked == true) {
                    showAcrylic(color);
                  } else {
                    closeAcrylic();
                  }
                },
              ),
              MenuItem.checkbox(
                checked: true,
                label: "窗口置顶",
                onClick: (MenuItem menuItem) {
                  menuItem.checked = !(menuItem.checked == true);
                  if (kDebugMode) {
                    print("窗口置顶 onClick ${menuItem.checked}");
                  }
                  if (menuItem.checked == true) {
                    windowManager.setAlwaysOnTop(true);
                  } else {
                    windowManager.setAlwaysOnTop(false);
                  }
                },
              ),
              MenuItem.checkbox(
                checked: true,
                label: "自启动",
                onClick: (MenuItem menuItem) {
                  menuItem.checked = !(menuItem.checked == true);
                  if (kDebugMode) {
                    print("自启动 onClick ${menuItem.checked}");
                  }
                },
              ),
              //可选类型的菜单栏
              MenuItem.checkbox(
                checked: true,
                label: "图标闪烁",
                onClick: (MenuItem menuItem) {
                  menuItem.checked = !(menuItem.checked == true);
                  if (kDebugMode) {
                    print("图标闪烁 onClick ${menuItem.checked}");
                  }
                },
              ),
            ])),
        //分割线
        MenuItem.separator(),
        MenuItem(
            key: 'open_app',
            label: 'Open App',
            icon: Platform.isWindows
                ? 'assets/images/tray_icon_original.ico'
                : 'assets/images/img_1.png',
            onClick: (MenuItem menuItem) {
              windowManager.show();
            }),
        MenuItem(
            key: 'exit_app',
            label: 'Exit App',
            icon: Platform.isWindows
                ? 'assets/images/tray_icon_original.ico'
                : 'assets/images/img_1.png',
            onClick: (MenuItem menuItem) {
              windowManager.close();
            }),
      ],
    );
    if (kDebugMode) {
      print("menu:${menu.toJson()}");
    }
    //为系统托盘配置菜单
    await trayManager.setContextMenu(menu);
  }

  // Future<void> _initSystemTray() async {
  //   await _systemTray.initSystemTray(
  //     iconPath: Platform.isWindows
  //         ? 'assets/images/tray_icon_original.ico'
  //         : 'assets/images/img_1.png',
  //   );
  //   _systemTray.setTitle("system tray");
  //   _systemTray.setToolTip("How to use system tray with Flutter");
  //   // handle system tray event
  //   _systemTray.registerSystemTrayEventHandler((eventName) {
  //     debugPrint("eventName: $eventName");
  //     if (eventName == kSystemTrayEventClick) {
  //       Platform.isWindows
  //           ? windowManager.show()
  //           : _systemTray.popUpContextMenu();
  //     } else if (eventName == kSystemTrayEventRightClick) {
  //       Platform.isWindows
  //           ? _systemTray.popUpContextMenu()
  //           : windowManager.show();
  //     }
  //   });
  //   final Menu _menuMain = Menu();
  //   await _menuMain.buildFrom([
  //     SubMenu(
  //         label: "窗口设置",
  //         image: Platform.isWindows
  //             ? 'assets/images/app_icon.bmp'
  //             : 'assets/images/img_1.png',
  //         children: [
  //           MenuItemCheckbox(
  //               label: "毛玻璃效果",
  //               checked: true,
  //               name: 'acrylic_cb',
  //               onClicked: (MenuItemBase menuItem) async {
  //                 await menuItem.setCheck(!menuItem.checked);
  //                 if (kDebugMode) {
  //                   print("毛玻璃效果 onClick ${menuItem.checked}");
  //                 }
  //                 if (menuItem.checked == true) {
  //                   showAcrylic(color);
  //                 } else {
  //                   closeAcrylic();
  //                 }
  //               }),
  //           MenuItemCheckbox(
  //               label: "窗口置顶",
  //               checked: true,
  //               onClicked: (MenuItemBase menuItem) async {
  //                 await menuItem.setCheck(!menuItem.checked);
  //                 if (kDebugMode) {
  //                   print("窗口置顶 onClick ${menuItem.checked}");
  //                 }
  //                 if (menuItem.checked == true) {
  //                   windowManager.setAlwaysOnTop(true);
  //                 } else {
  //                   windowManager.setAlwaysOnTop(false);
  //                 }
  //               }),
  //           MenuItemCheckbox(
  //               label: "自启动",
  //               checked: true,
  //               name: 'auto_start_cb',
  //               onClicked: (MenuItemBase menuItem) async {
  //                 // menuItem.checked = !(menuItem.checked == true);
  //                 await menuItem.setCheck(!menuItem.checked);
  //                 if (kDebugMode) {
  //                   print("自启动 onClick ${menuItem.checked}");
  //                 }
  //               }),
  //           MenuItemCheckbox(
  //               label: "图标闪烁",
  //               checked: true,
  //               name: "flash_cb",
  //               onClicked: (MenuItemBase menuItem) async {
  //                 MenuItemCheckbox? flashCb =
  //                 _menuMain.findItemByName<MenuItemCheckbox>("flash_cb");
  //                 await flashCb?.setCheck(!menuItem.checked);
  //                 if (kDebugMode) {
  //                   print("图标闪烁 onClick ${menuItem.checked}");
  //                 }
  //               }),
  //         ]),
  //     MenuSeparator(),
  //     MenuItemLabel(
  //         label: 'Open App',
  //         image: Platform.isWindows
  //             ? 'assets/images/app_icon.bmp'
  //             : 'assets/images/img_1.png',
  //         onClicked: (MenuItemBase menuItem) {
  //           windowManager.show();
  //         }),
  //     MenuItemLabel(
  //         label: 'Exit App',
  //         image: Platform.isWindows
  //             ? 'assets/images/app_icon.bmp'
  //             : 'assets/images/img_1.png',
  //         onClicked: (MenuItemBase menuItem) {
  //           windowManager.close();
  //         }),
  //   ]);
  //   if (kDebugMode) {
  //     print("menu:${_menuMain.toString()}");
  //   }
  //   await _systemTray.setContextMenu(_menuMain);
  //   showAcrylic(color);
  //   setState(() {});
  // }

  @override
  void dispose() {
    windowManager.removeListener(this);
    trayManager.removeListener(this);
    //销毁系统托盘
    trayManager.destroy();
    super.dispose();
  }

  @override
  void onWindowEvent(String eventName) {
    print("event:$eventName");
    super.onWindowEvent(eventName);
  }

  @override
  void onWindowBlur() {
    print("onWindowBlur");
    super.onWindowBlur();
  }

  @override
  void onWindowClose() async {
    var isPreventClose = await windowManager.isPreventClose();
    if (!context.mounted) return;
    if (isPreventClose) {
      print("custom close  action");
      showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: const Text("提示"),
              actions: [
                TextButton.icon(
                    onPressed: () {
                      Navigator.of(context).pop();
                      windowManager.destroy();
                    },
                    icon: const Icon(Icons.close),
                    label: const Text("确认")),
                TextButton.icon(
                    onPressed: () {
                      print("取消");
                      Navigator.of(context).pop();
                      var height = MediaQuery.of(context).size.height;
                      var width = MediaQuery.of(context).size.width;
                      print("size:${MediaQuery.of(context).size}");
                      print("size:${window.physicalSize}");
                      print("size:${MediaQuery.of(context).devicePixelRatio}");
                      print(
                          "size:height${MediaQuery.of(context).devicePixelRatio * height},width:${MediaQuery.of(context).devicePixelRatio * width}");
                    },
                    icon: const Icon(Icons.remove),
                    label: const Text("取消")),
              ],
            );
          });
    } else {
      print("use system close action");
    }
    print("onWindowClose");
    super.onWindowClose();
  }

  @override
  void onWindowDocked() {
    print("onWindowDocked");
    super.onWindowDocked();
  }

  @override
  void onWindowEnterFullScreen() {
    print("onWindowEnterFullScreen");
    super.onWindowEnterFullScreen();
  }

  @override
  void onWindowFocus() {
    // TODO: implement onWindowFocus
    super.onWindowFocus();
    print("onWindowEnterFullScreen");
    setState(() {});
  }

  @override
  void onWindowLeaveFullScreen() {
    // TODO: implement onWindowLeaveFullScreen
    super.onWindowLeaveFullScreen();
    print("onWindowLeaveFullScreen");
  }

  @override
  void onWindowMaximize() {
    // TODO: implement onWindowMaximize
    super.onWindowMaximize();
    print("onWindowMaximize");
  }

  @override
  void onWindowMinimize() {
    // TODO: implement onWindowMinimize
    super.onWindowMinimize();
    print("onWindowMinimize");
  }

  @override
  void onWindowMove() {
    // TODO: implement onWindowMove
    super.onWindowMove();
    print("onWindowMove");
  }

  @override
  void onWindowMoved() {
    // TODO: implement onWindowMoved
    super.onWindowMoved();
    print("onWindowMove");
  }

  @override
  void onWindowResize() {
    // TODO: implement onWindowResize
    super.onWindowResize();
    print("onWindowResize");
  }

  @override
  void onWindowResized() {
    // TODO: implement onWindowResized
    super.onWindowResized();
    print("onWindowResized");
  }

  @override
  void onWindowRestore() {
    // TODO: implement onWindowRestore
    super.onWindowRestore();
    print("onWindowRestore");
  }

  @override
  void onWindowUndocked() {
    // TODO: implement onWindowUndocked
    super.onWindowUndocked();
    print("onWindowUndocked");
  }

  @override
  void onWindowUnmaximize() {
    // TODO: implement onWindowUnmaximize
    super.onWindowUnmaximize();
    print("onWindowUnmaximize");
  }

  @override
  void onTrayIconRightMouseUp() {
    // TODO: implement onTrayIconRightMouseUp
    super.onTrayIconRightMouseUp();
    if (kDebugMode) {
      print("onTrayIconMouseUp");
    }
  }
  @override
  void onTrayIconMouseUp() {
    super.onTrayIconMouseUp();
    if (kDebugMode) {
      print("onTrayIconMouseUp");
    }
  }
  @override
  void onTrayIconMouseDown() {
    if (kDebugMode) {
      print("onTrayIconMouseDown");
    }
    windowManager.show();
  }

  @override
  void onTrayIconRightMouseDown() {
    if (kDebugMode) {
      print("onTrayIconRightMouseDown");
    }
    trayManager.popUpContextMenu();
  }

  @override
  void onTrayMenuItemClick(MenuItem menuItem) {
    if (kDebugMode) {
      print("menuItem:${menuItem.key}-${menuItem.label}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.transparent,
        body: DragToMoveArea(
          child: Column(mainAxisSize: MainAxisSize.max, children: [
            TitleBarWidget(),
            Expanded(child: WindowBodyWidget()),
            // ElevatedButton(
            //     onPressed: () async {
            //       InterfaceBrightness brightness = Platform.isMacOS
            //           ? InterfaceBrightness.auto
            //           : InterfaceBrightness.dark;
            //       const regCurrentVersionKey =
            //           r'SOFTWARE\Microsoft\Windows NT\CurrentVersion';
            //       final key = Registry.openPath(RegistryHive.localMachine,
            //           path: regCurrentVersionKey);
            //
            //       final buildNumber = key.getValueAsInt('UBR');
            //       WindowEffect effect;
            //       if (buildNumber! >= 1803) {
            //         effect = WindowEffect.acrylic;
            //       } else {
            //         effect = WindowEffect.aero;
            //       }
            //       print("effect:$effect");
            //       Color color = Platform.isWindows
            //           ? const Color(0xb3ffffff)
            //           : Colors.transparent;
            //       await Window.setEffect(
            //           effect: effect,
            //           color: color,
            //           dark: brightness == InterfaceBrightness.dark);
            //       if (Platform.isMacOS) {
            //         if (brightness != InterfaceBrightness.auto) {
            //           Window.overrideMacOSBrightness(
            //             dark: brightness == InterfaceBrightness.dark,
            //           );
            //         }
            //       }
            //
            //       key.close();
            //
            //       final width = GetSystemMetrics(SM_CXSCREEN );
            //       final height = GetSystemMetrics(SM_CYSCREEN );
            //       print("width:$width");
            //       print("height:$height");
            //     },
            //     child: const Text("查询注册表")),
            // Image.asset("assets/images/img_1.png"),
          ]),
        ),
      ),
    );
  }
}
